package com.itheima.datastructure.demo1;

public class AvgArray {
    public static void main(String[] args) {
        System.out.println(findMaxAverage(new int[]{1, 12, -5, -6, 50, 3}, 4));
    }

    public static double findMaxAverage(int[] nums, int k) {
        // 输入参数有效性检查
        if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
            throw new IllegalArgumentException("Invalid input parameters");
        }

        int n = nums.length;

        // 特殊情况处理：当 k 等于数组长度时，直接返回整个数组的平均值
        if (k == n) {
            return sumArray(nums) / (double) k;
        }

        int sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        int max = sum;

        for (int i = k; i < n; i++) {
            sum = sum - nums[i - k] + nums[i];
            max = Math.max(max, sum);
        }

        return 1.0 * max / k;
    }

    // 辅助方法：计算数组元素的和
    private static int sumArray(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        return sum;
    }
}
